package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.ruoyi.common.constant.Constants;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @ClassName RequestGetBodyUtils
 * @Description TODO
 * @Author drx
 * @Date 2023/5/31 14:18
 */
public class RequestGetBodyUtils {
    protected final static Log logger = LogFactory.getLog(RequestGetBodyUtils.class);

    public static JSONObject getBody() {
        JSONObject jsonObject=new JSONObject();
        try{
            HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);

            jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
        }catch(IOException e){
            logger.error("获取分页JSON参数错误！");
        }
        return jsonObject;
    }
    public static  JSONObject formatPageJson(JSONObject jsonObject){
        if(jsonObject==null) jsonObject=new JSONObject();
        if(!jsonObject.containsKey(Constants.PAGE_NUM))jsonObject.put(Constants.PAGE_NUM,null);
        if(!jsonObject.containsKey(Constants.PAGE_SIZE))jsonObject.put(Constants.PAGE_SIZE,null);
        if(!jsonObject.containsKey(Constants.ORDER_BY_COLUMN))jsonObject.put(Constants.ORDER_BY_COLUMN,"");
        if(!jsonObject.containsKey(Constants.IS_ASC))jsonObject.put(Constants.IS_ASC,"");
        return jsonObject;
    }
}
